package org.yagnus.calendar.impl;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

import org.yagnus.calendar.BaseCalendarSchedule;

/**
 * This implements day of field class that allows for days from end queries. the
 * parameter specifies which field (day of week or day of month or day of year)
 * The input index (ith day of X) is computed modulo the maximum field value.
 * This allows us to look up -1 as the last element.
 * 
 * @author u
 * 
 */
public class DaysOfScheduler extends BaseCalendarSchedule {

	final Set<Integer> days = new HashSet<Integer>();
	final Set<Integer> daysFromEnd = new HashSet<Integer>();
	final int field;

	/**
	 * Specify days from Calendar's constants. We expect 0-based input here, 0
	 * means first day, 1 second day, -1 last day, etc.
	 */
	public DaysOfScheduler(int field, int... inputDays) {
		this.field = field;
		if (days != null) {
			for (Integer i : inputDays)
				if (i >= 0)
					days.add(i);
				else
					daysFromEnd.add(i);
		}
	}

	public boolean happensOn(Calendar testDay) {
		// since Calendar returns human redable 1-based days
		int fieldValue = testDay.get(field) - 1;
		return days.contains(fieldValue)
				|| daysFromEnd.contains(fieldValue
						- testDay.getActualMaximum(field));
	}
}
